<?php

namespace LhpAmis\Traits;

use EasyAdmin\tool\CommonTool;
use LhpAmis\Renderers\Amis;

trait RequestTrait
{
    /**
     * 是否关联查询
     * @var bool
     */
    protected $relationSearch = false;
    /**
     * 构建请求参数
     * @param array $excludeFields 忽略构建搜索的字段
     * @return array
     */
    protected function buildTableParames($excludeFields = [])
    {
        $get = $this->request->get('', null, null);
        $page = isset($get['page']) && !empty($get['page']) ? $get['page'] : 1;
        $limit = isset($get['limit']) && !empty($get['limit']) ? $get['limit'] : 15;
        $filters = isset($get['filter']) && !empty($get['filter']) ? $get['filter'] : '{}';
        $ops = isset($get['op']) && !empty($get['op']) ? $get['op'] : '{}';
        // json转数组
        $filters = json_decode($filters, true);
        $ops = json_decode($ops, true);
        $where = [];
        $excludes = [];

        // 判断是否关联查询
        $tableName = CommonTool::humpToLine(lcfirst($this->model->getName()));

        foreach ($filters as $key => $val) {
            $val = trim($val);
            if (in_array($key, $excludeFields)) {
                $excludes[$key] = $val;
                continue;
            }
            $op = isset($ops[$key]) && !empty($ops[$key]) ? $ops[$key] : '%*%';
            if ($this->relationSearch && count(explode('.', $key)) == 1) {
                $key = "{$tableName}.{$key}";
            }
            switch (strtolower($op)) {
                case '=':
                    $where[] = [$key, '=', $val];
                    break;
                case '%*%':
                    $where[] = [$key, 'LIKE', "%{$val}%"];
                    break;
                case '*%':
                    $where[] = [$key, 'LIKE', "{$val}%"];
                    break;
                case '%*':
                    $where[] = [$key, 'LIKE', "%{$val}"];
                    break;
                case 'in':
                    $where[] = [$key, 'find in set', $val];
                    break;
                case 'range':
                    [$beginTime, $endTime] = explode(' - ', $val);
                    if (in_array('create_time', explode('.', $key)) || in_array('update_time', explode('.', $key))) {
                        $where[] = [$key, '>=', strtotime($beginTime)];
                        $where[] = [$key, '<=', strtotime($endTime)];
                    } else {
                        $where[] = [$key, '>=', $beginTime];
                        $where[] = [$key, '<=', $endTime];
                    }
                    break;
                default:
                    $where[] = [$key, $op, "%{$val}"];
            }
        }
        return [$page, $limit, $where, $excludes];
    }
    /**
     * 处理请求数据为where条件
     * @param mixed $method
     * @return array
     */
    protected function RequestData()
    {
        $request = request()->param();

        $where = [];
        $page = [];
        $order = $this->order($request);
        $page = $this->page($request);

        foreach ($request as $name => $value) {

            if ($value == '') {
                continue;
            }
            if (is_array($value)) {
                $where[] = $value;
            } else {
                // username$filter|text
                // (user|username)$filter|text
                // (user|sort)$filter|text
                $formType = null;
                if (strpos($name, '$') !== false && strpos($name, '|') !== false) {
                    [$name, $type] = explode('$', $name);
                    [$formType, $type] = explode('|', $type);
                }

                if ($value === false) {
                    $value = 0;
                } elseif ($value === true) {
                    $value = 1;
                }
                if ($formType == 'filter') {

                    if (strpos($name, '|') !== false) {
                        $name = str_replace('|', '.', $name);
                    }
                    if (in_array($type, ['select', 'radio', 'checkbox'])) {
                        $where[] = [$name, '=', $value];
                    } elseif (in_array($type, ['date', 'time', 'datetime', 'month', 'quarter', 'year'])) {

                        switch ($type) {
                            case 'time':
                                $where[] = $this->isValidTimeRange($name, $value);
                                break;
                            case 'date':
                            case 'datetime':
                            case 'month':
                            case 'quarter':
                            case 'year':
                                $where[] = $this->isValidDateRange($name, $value);
                                break;
                            default:
                                $where[] = [$name, '=', $value];
                        }
                    } else {
                        if (strpos($name, '->') !== false) {
                            $where[] = [$name, 'json_contains', [$value]];
                        } else {
                            $where[] = [$name, 'like', "%{$value}%"];
                        }
                    }
                } else {
                    $where[] = [$name, '=', $value];
                }
            }
        }


        return [$where, $page, $order];
    }
    /**
     * 处理请求数据为where条件
     * @param mixed $method
     * @return array 根据关联表返回各自的条件
     */
    protected function RequestDataWith($isJoinTableAndName = true)
    {
        $request = request()->param();

        $where = [];
        $page = [];
        $order = $this->order($request);
        $page = $this->page($request);
        $baseTable = '-';
        foreach ($request as $name => $value) {

            if ($value == '') {
                continue;
            }
            if (is_array($value)) {
                $where[] = $value;
            } else {
                // username$filter|text
                // (user|username)$filter|text
                // (user|sort)$filter|text
                $formType = null;
                if (strpos($name, '$') !== false && strpos($name, '|') !== false) {
                    [$name, $type] = explode('$', $name);
                    [$formType, $type] = explode('|', $type);
                }

                if ($value === false) {
                    $value = 0;
                } elseif ($value === true) {
                    $value = 1;
                }
                if ($formType == 'filter') {

                    if (strpos($name, '|') !== false) {
                        [$table, $name] = explode('|', $name);
                        if ($isJoinTableAndName) {
                            $name = $table . '.' . $name;
                        }
                    } else {
                        $table = $baseTable;
                    }
                    if (in_array($type, ['select', 'radio', 'checkbox'])) {
                        $where[$table][] = [$name, '=', $value];
                    } elseif (in_array($type, ['date', 'time', 'datetime', 'month', 'quarter', 'year'])) {

                        switch ($type) {
                            case 'time':
                                $where[$table][] = $this->isValidTimeRange($name, $value);
                                break;
                            case 'date':
                            case 'datetime':
                            case 'month':
                            case 'quarter':
                            case 'year':
                                $where[$table][] = $this->isValidDateRange($name, $value);
                                break;
                            default:
                                $where[$table][] = [$name, '=', $value];
                        }
                    } else {
                        if (strpos($name, '->') !== false) {
                            $where[$table][] = [$name, 'json_contains', [$value]];
                        } else {
                            $where[$table][] = [$name, 'like', "%{$value}%"];
                        }
                    }
                } else {
                    $where[$table][] = [$name, '=', $value];
                }
            }
        }


        return [$where, $page, $order];
    }
    private function page(&$request)
    {
        $page = [];
        if (isset($request['page'])) {
            $page['page'] = (int) $request['page'];
            unset($request['page']);
        }

        if (isset($request['list_rows'])) {
            $page['list_rows'] = (int) $request['list_rows'];
            unset($request['list_rows']);
        }

        if (isset($request['perPage'])) {
            $page['list_rows'] = (int) $request['perPage'];
            unset($request['perPage']);
        }
        if (empty($page)) {
            $page['list_rows'] = 15;
        }

        return $page;
    }
    private function order(&$request)
    {
        $page = [];
        if (isset($request['orderDir'])) {
            $page = [$request['orderBy'] => $request['orderDir']];
            unset($request['orderBy']);
            unset($request['orderDir']);
        }
        return $page;
    }
    /**
     * 判断并获取逗号分隔时间戳字符串
     * @param mixed $name
     * @param mixed $input
     * @return mixed
     */
    function isValidTimestampRange($name, $input)
    {
        if (!is_string($input)) {
            return $input;
        }
        // 检查字符串是否包含逗号
        if (strpos($input, ',') === false) {
            return $input;
        }

        // 分割字符串
        list($timestamp1, $timestamp2) = explode(',', $input);

        // 去除可能的空格
        $timestamp1 = (int) trim($timestamp1);
        $timestamp2 = (int) trim($timestamp2);

        // 检查是否为数字
        if (!is_numeric($timestamp1) || !is_numeric($timestamp2)) {
            return $input;
        }

        // 检查是否为有效的时间戳
        if (!is_int((int) $timestamp1) || !is_int((int) $timestamp2)) {
            return $input;
        }

        // 检查时间戳范围是否合理（例如，第一个时间戳应小于第二个时间戳）
        if ((int) $timestamp1 >= (int) $timestamp2) {
            return $input;
        }

        return [$name, 'between', [$timestamp1, $timestamp2]];
    }
    function isValidDataTimestampRange($name, $input)
    {
        if (!is_string($input)) {
            return $input;
        }
        // 检查字符串是否包含逗号
        if (strpos($input, ',') === false) {
            return $input;
        }

        // 分割字符串
        list($timestamp1, $timestamp2) = explode(',', $input);

        // 去除可能的空格
        $timestamp1 = trim($timestamp1);
        $timestamp2 = trim($timestamp2);

        // 检查是否为数字
        if (!is_numeric($timestamp1) || !is_numeric($timestamp2)) {
            return $input;
        }

        // 检查是否为有效的时间戳
        if (!is_int((int) $timestamp1) || !is_int((int) $timestamp2)) {
            return $input;
        }

        // 检查时间戳范围是否合理（例如，第一个时间戳应小于第二个时间戳）
        if ((int) $timestamp1 >= (int) $timestamp2) {
            return $input;
        }

        return [$name, 'between', [$timestamp1, $timestamp2]];
    }

    /**
     * 判断并获取逗号分隔时间字符串
     * @param mixed $input
     * @return array
     */
    function isValidDateRange($name, $input)
    {
        if (!is_string($input)) {
            return [$name, '=', $input];
        }
        // 检查字符串是否包含逗号
        if (strpos($input, ',') === false) {
            return [$name, '=', $input];
        }

        // 分割字符串
        list($date1, $date2) = explode(',', $input);

        // 去除可能的空格
        $timestamp1 = trim($date1);
        $timestamp2 = trim($date2);

        // 检查时间戳范围是否合理（例如，第一个日期应小于第二个日期）
        if ($timestamp1 > $timestamp2) {
            return $input;
        }

        return [$name, 'between', [$timestamp1, $timestamp2]];
    }
    function isValidTimeRange($name, $input)
    {
        if (!is_string($input)) {
            return $input;
        }
        // 检查字符串是否包含逗号
        if (strpos($input, ',') === false) {
            return $input;
        }

        // 分割字符串
        list($time1, $time2) = explode(',', $input);

        // 去除可能的空格
        $time1 = trim($time1);
        $time2 = trim($time2);

        // 检查时间戳范围是否合理（例如，第一个日期应小于第二个日期）
        $timestamp1 = strtotime(date('Y-m-d ' . $time1 . ':00'));
        $timestamp2 = strtotime(date('Y-m-d ' . $time2 . ':59'));
        if ($timestamp1 >= $timestamp2) {
            return $input;
        }

        return [$name, 'between', [$timestamp1, $timestamp2]];
    }

    protected function withWhere($field = [], $where = [])
    {
        return function ($query) use ($field, $where) {
            // 处理查询条件
            if (!empty($where)) {
                // 支持数组形式条件和闭包条件
                if (is_array($where)) {

                    foreach ($where as $itemWhere) {

                        $query->where($itemWhere);
                    }
                    $query->where($where);
                } elseif ($where instanceof \Closure) {
                    $where($query);
                }
            }

            // 处理字段筛选
            if (!empty($field)) {
                $query->field(join(',', $field));
            } else {
                $query->field('*');
            }
            // 未指定字段时不调用field方法，使用默认行为
        };
    }

}
